<template lang="pug">
  .page
    //- 筛选部分
    .search-form.mb-10.pl-10.pr-10
      Form.ivu-row(ref="formData" :model="formData" :rules="rules" :label-width="60" :label-colon="true")
        FormItem.form-item.ivu-col.pr-20.mb-15(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
          template(v-if="item.type === 'input'")
            Input(v-model="formData[item.model]" :placeholder="item.placeholder" clearable)
          template(v-if="item.type === 'datePicker'")
            DatePicker.w-100(v-model="formData[item.model]" :placeholder="item.placeholder" type="date")
          template(v-if="item.type === 'select'")
            Select(v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable @on-change="handleSelectChange(item.model, $event)")
              Option(
                v-for="(c_item, c_index) in arrListDown[item.options]"
                :value="c_item.value"
                :key="c_index"
              ) {{ c_item.label }}
          template(v-if="item.type === 'button'")
            Button(type="info" @click="searchFn") 查询

    .date-bg
      //- 说明文字
      .ivu-row.font-14.mb-20
        .ivu-col.ivu-col-span-12.line-h-32
          |本月合同目标：
          span.text-info.pr-30 {{monthBaseData.month_BillingTarget}}元
          |本周合同目标：
          span.text-info.pr-30 {{monthBaseData.week_BillingTarget}}元
          |本周商机目标：
          span.text-info.pr-15 A:{{monthBaseData.businessTargetA}}
          span.text-info.pr-15 B:{{monthBaseData.businessTargetB}}
          span.text-info.pr-15 C:{{monthBaseData.businessTargetC}}
        .ivu-col.ivu-col-span-12.text-right
          //- Button.mr-10(type="info") 新建企业客户
          Button.mr-10(type="info" @click="handleShowAddPlanModal" :disabled="diffDate < 0") 新建计划

      .clearfix.date-tab
        .date-tab-arrow.arrow-prev(@click="getPrevWeekDays")
          i.ivu-icon.ivu-icon-ios-arrow-back.font-24
        .date-tab-arrow.arrow-next(@click="getNextWeekDays")
          i.ivu-icon.ivu-icon-ios-arrow-forward.font-24

        //- 日历表格
        //- Tabs(type="card" :animated="false" :value="today" @on-click="handleClickTabs")
        //-   TabPane(:label="item.date + item.label" :name="item.date" v-for="item of tabsArr")
        .tabs-title
          .tabs-title-item(v-for="(item, index) of tabsArr" :key="index" @click="handleClickTabs(index, item.date)" :class="today == item.date ? 'active' : ''") {{$moment(item.date).format('MM月DD日')}} {{item.label}}

        .date-wrap.pall-20
          //- 标题栏
          .ivu-row.date-subTitle
            .ivu-col.ivu-col-span-4 -
            .ivu-col.ivu-col-span-5 今日重点
            .ivu-col.ivu-col-span-5 上午工作
            .ivu-col.ivu-col-span-5 下午工作
            .ivu-col.ivu-col-span-5 备注

          //- 工作计划
          .ivu-row.date-content
            .ivu-col.ivu-col-span-4.left-title 工作计划
            .ivu-col.ivu-col-span-5(v-for="(box, index) of planItem" :key="index")
              .date-box-wrap(:class="currentSection === 'planItem' && currentKey === box.key ? 'active' : ''")
                .clearfix.text-info.edit(@click="handleEdit('planItem', box.key, box.keyName)")
                  i.ivu-icon.ivu-icon-md-create.font-18.pull-left.mr-5
                  span.pull-left 编辑
                //- 填写内容
                .date-edit-wrap(v-if="currentSection === 'planItem' && currentKey === box.key")
                  //- Input(v-model="writeContent" type="textarea" :autosize="{minRows: 2,maxRows: 10}" placeholder="请输入…")
                  .add-plan-editor.editor-180
                    quill-editor(
                      v-model="writeContent"
                      :options="editorOption"
                    )
                  .text-center.date-edit-btns
                    Button.mr-10(type="info" @click="updatePlan('planItem', box.key, box.keyName)") 保存
                    Button(type="info" @click="handleCancel") 取消
                //- 显示文字
                .date-text(v-else v-html="planData[box.keyName]")
                  //- pre {{planData[box.key]}}

          //- 工作完成
          .ivu-row.date-content
            .ivu-col.ivu-col-span-4.left-title 工作完成
            .ivu-col.ivu-col-span-5(v-for="(box, index) of finishItem" :key="index")
              .date-box-wrap(:class="currentSection === 'finishItem' && currentKey === box.key ? 'active' : ''")
                .clearfix.text-info.edit(@click="handleEdit('finishItem', box.key, box.keyName)")
                  i.ivu-icon.ivu-icon-md-create.font-18.pull-left.mr-5
                  span.pull-left 编辑
                //- 填写内容
                .date-edit-wrap(v-if="currentSection === 'finishItem' && currentKey === box.key")
                  //- Input(v-model="writeContent" type="textarea" :autosize="{minRows: 2,maxRows: 10}" placeholder="请输入…")
                  .add-plan-editor.editor-180
                    quill-editor(
                      v-model="writeContent"
                      :options="editorOption"
                    )
                  .text-center.date-edit-btns
                    Button.mr-10(type="info" @click="updatePlan('finishItem', box.key, box.keyName)") 保存
                    Button(type="info" @click="handleCancel") 取消
                //- 显示文字
                .date-text(v-else v-html="finishData[box.keyName]")
                  //- pre {{finishData[box.key]}}

    //- 新建本周工作计划弹窗
    AddPlanModal(ref="AddPlanModal" @query="query(today)" :today="today" :userId="userId")
</template>

<script>
import { Common } from '@/utils/common.js'
import AddPlanModal from './modal/addPlanModal.vue'
import { WorkDayPlanApi } from '@/api/WorkDayPlan.api.js'

import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import '@/assets/styles/dailyManage.less';

const toolbarOptions = [
  [{ 'align': [] }],
  [{ 'color': [] }, { 'background': [] }]
]

export default {
  name: '',

  components: {
    AddPlanModal,
    quillEditor
  },

  data () {
    return {
      userId: null,
      monthBaseData: {
        month_BillingTarget: null,
        week_BillingTarget: null,
        businessTargetA: null,
        businessTargetB: null,
        businessTargetC: null
      },
      formData: {
        date: '',
        userId: ''
      },
      formItem: [
        { type: 'datePicker', label: '日期', placeholder: '请选择日期', prop: 'date', model: 'date', style: 'ivu-col-span-6' },
        { type: 'select', label: '员工', placeholder: '请选择员工', prop: 'userId', model: 'userId', style: 'ivu-col-span-6', options: 'userList' },
        { type: 'button', style: 'ivu-col-span-6' }
      ],
      rules: {},
      arrListDown: {
        userList: []
      },
      tabsArr: [
        { name: 'Mon', label: ' 星期一', date: '', content: '' },
        { name: 'Tue', label: ' 星期二', date: '', content: '' },
        { name: 'Wed', label: ' 星期三', date: '', content: '' },
        { name: 'Thu', label: ' 星期四', date: '', content: '' },
        { name: 'Fri', label: ' 星期五', date: '', content: '' },
        { name: 'Sat', label: ' 星期六', date: '', content: '' },
        { name: 'Sun', label: ' 星期日', date: '', content: '' }
      ],
      planData: {
        keyNote_Plan: '',
        morning_Plan: '',
        afternoon_Plan: '',
        remark_Plan: ''
      },
      planItem: [
        { type: 'box', key: '1', keyName: 'keyNote_Plan', title: '今日重点', style: '', content: '--', parsingContent: '' },
        { type: 'box', key: '6', keyName: 'morning_Plan', title: '上午工作', style: '', content: '--', parsingContent: '' },
        { type: 'box', key: '11', keyName: 'afternoon_Plan', title: '下午工作', style: '', content: '--', parsingContent: '' },
        { type: 'box', key: '16', keyName: 'remark_Plan', title: '备注', style: '', content: '--', parsingContent: '' }
      ],
      finishData: {
        keyNote_Complete: '',
        morning_Complete: '',
        afternoon_Complete: '',
        remark_Complete: ''
      },
      finishItem: [
        { type: 'box', key: '2', keyName: 'keyNote_Complete', title: '今日重点', style: '', content: '--', parsingContent: '' },
        { type: 'box', key: '7', keyName: 'morning_Complete', title: '上午工作', style: '', content: '--', parsingContent: '' },
        { type: 'box', key: '12', keyName: 'afternoon_Complete', title: '下午工作', style: '', content: '--', parsingContent: '' },
        { type: 'box', key: '17', keyName: 'remark_Complete', title: '备注', style: '', content: '--', parsingContent: '' }
      ],
      currentSection: '', // 点击的行-工作计划/工作完成
      currentKey: '', // 点击的块-今日重点/上午工作/下午工作/备注
      writeContent: '',
      today: this.$moment(new Date()).format('YYYY-MM-DD'),
      selectDate: null, // 选择的日期
      selectDateNum: 0,
      editorOption: {
        modules: {
          toolbar: {
            container: toolbarOptions
          }
        }
      },
      diffDate: 0
    }
  },

  computed: {
  },

  created () {
    this.userId = JSON.parse(localStorage.getItem('clientLoginInfo')).data.userId
  },

  mounted () {
    this.getUserList()
    this.getCurrWeekDays()
  },

  methods: {
    // 点击切换tab
    handleClickTabs (index, date) {
      this.today = date
      this.getCurrWeekDays(date)
    },

    // 点击编辑图标
    handleEdit (section, key, keyName) {
      this.currentSection = section
      this.currentKey = key
      // this.writeContent = ''
      if (section === 'planItem') {
        this.writeContent = this.planData[keyName]
      } else if (section === 'finishItem') {
        this.writeContent = this.finishData[keyName]
      }
    },

    // 点击保存编辑的内容
    async updatePlan (section, key, keyName) {
      console.log('section: ', section, ', key: ', key, ', keyName: ', keyName)
      var params = {
        userId: this.formData.userId ? this.formData.userId : this.userId,
        date: this.today,
        type: key,
        content: this.writeContent
      }
      let res = await WorkDayPlanApi.updatePlan(params)
      console.log('保存修改的工作计划res: ', res)
      if (res.status === 200 && res.data.success) {
        if (section === 'planItem') {
          this.planData[keyName] = this.writeContent
          console.log('🚩 this.planData: ', this.planData)
        } else if (section === 'finishItem') {
          this.finishData[keyName] = this.writeContent
          console.log('🚩 this.finishData: ', this.finishData)
        }
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }

      this.handleCancel()
    },

    // 取消编辑
    handleCancel () {
      this.writeContent = ''
      this.currentSection = ''
      this.currentKey = ''
    },

    // 获取当前周的开始至结束日期
    getCurrWeekDays (selectDate) {
      let tempDate = selectDate || new Date()
      let date = []
      let week = this.$moment(tempDate)
      let vWeekOfDay = this.$moment().format('E') // 算出这周的周几
      let cWeekOfDay = this.$moment(tempDate).format('E') // 点击的日期是这周的周几
      let mon = week.startOf('week').format('YYYY-MM-DD') // 周初
      let sun = week.endOf('week').format('YYYY-MM-DD') // 周末
      let tempArr = []
      for (var i = 0; i < 7; i++) {
        this.tabsArr[i].date = this.$moment(mon, 'YYYY-MM-DD').add(i, 'days').format('YYYY-MM-DD')
      }

      // 计算选择的日期/当前日期 距离今天的天数
      let diffDate = this.$moment(tempDate).diff(this.$moment(new Date()).startOf('day'), 'days')
      this.diffDate = diffDate
      console.log('🌈 当前点击的日期是一周中的第(cWeekOfDay)', cWeekOfDay, '天 跟现在相差(diffDate): ', Math.abs(diffDate), '天')
      if (diffDate < 0) { // 选择的是当天以前的日期
        if (Math.abs(diffDate) < vWeekOfDay) {
          this.selectDateNum = 0
        } else if (Math.abs(cWeekOfDay) == 1) {
          this.selectDateNum = parseInt(Math.abs(diffDate) / 7) * -1
        } else {
          this.selectDateNum = Math.ceil(Math.abs(diffDate) / 7) * -1
        }
      } else { // 选择的是当天以后的日期
        if (Math.abs(diffDate) < (6 - vWeekOfDay)) {
          this.selectDateNum = 0
        } else if (Math.abs(cWeekOfDay) == 7) {
          this.selectDateNum = parseInt(Math.abs(diffDate) / 7)
        } else {
          this.selectDateNum = Math.ceil(Math.abs(diffDate) / 7)
        }
      }
      console.log('this.selectDateNum: ', this.selectDateNum)

      // 修改当前日期显示的内容
      this.today = selectDate ? this.$moment(selectDate).format('YYYY-MM-DD') : (Math.abs(this.selectDateNum) !== 0 ? mon : this.$moment(new Date()).format('YYYY-MM-DD'))
      console.log('selectDate: ', selectDate)
      console.log('this.today: ', this.today)
      this.query(this.today)
    },

    // 获取上周的开始至结束日期
    getPrevWeekDays () {
      this.selectDateNum--
      this.changeWeekDays()
    },

    // 获取下周的开始至结束日期
    getNextWeekDays () {
      this.selectDateNum++
      this.changeWeekDays()
    },

    // 点击前后星期时公用
    changeWeekDays (selectDate) {
      // console.log('⭐ this.selectDateNum ⭐: ', this.selectDateNum)
      let tempDate = selectDate || new Date()
      const mon = this.$moment(tempDate).day(7 * this.selectDateNum + 1).format('YYYY-MM-DD')
      const sun = this.$moment(tempDate).day(7 * this.selectDateNum + 7).format('YYYY-MM-DD')

      for (var i = 0; i < 7; i++) {
        this.tabsArr[i].date = this.$moment(mon, 'YYYY-MM-DD').add(i, 'days').format('YYYY-MM-DD')
      }

      // 修改当前日期显示的内容
      this.today = this.selectDateNum !== 0 ? mon : this.$moment(new Date()).format('YYYY-MM-DD')

      // 搜索栏里的日期显示改变后的日期
      // this.formData.aaa = this.$moment(tempDate).day(7 * this.selectDateNum + 1)

      this.getCurrWeekDays(this.today)
    },

    // 查询
    searchFn () {
      this.getCurrWeekDays(this.formData.date)
    },

    // 显示弹窗-新建本周工作计划
    handleShowAddPlanModal (row) {
      this.$refs.AddPlanModal.show()
      this.$refs.AddPlanModal.query(this.today)
    },

    // 根据用户ID+日期获取本天工作计划
    async query (date) {
      var params = {
        userId: this.formData.userId ? this.formData.userId : this.userId,
        date: date
      }
      let res = await WorkDayPlanApi.getPlan(params)
      console.log('本天工作计划res: ', res)
      if (res.status === 200 && res.data.success) {
        var data = res.data.data

        // 循环日历表顶部的月数据
        Object.keys(this.monthBaseData).forEach(key => {
          if (data[key]) {
            this.monthBaseData[key] = data[key]
          } else {
            this.monthBaseData[key] = '0'
          }
        })

        // 循环上午工作数据
        Object.keys(this.planData).forEach(key => {
          if (data[key]) {
            this.planData[key] = data[key]
          } else {
            this.planData[key] = '无'
          }
        })

        // 循环下午工作数据
        Object.keys(this.finishData).forEach(key => {
          if (data[key]) {
            this.finishData[key] = data[key]
          } else {
            this.finishData[key] = '无'
          }
        })
      } else {
        Object.keys(this.monthBaseData).forEach(key => {
          this.monthBaseData[key] = '0'
        })

        Object.keys(this.planData).forEach(key => {
          this.planData[key] = '无'
        })

        Object.keys(this.finishData).forEach(key => {
          this.finishData[key] = '无'
        })
      }
    },

    async getUserList () {
      let res = await WorkDayPlanApi.getUserList()
      console.log('员工列表res: ', res)
      var arr = []
      if (res.status === 200 && res.data.success) {
        // this.arrListDown.userList = res.data.data
        res.data.data.map(item => {
          arr.push({label: item.name, value: item.id})
        })
        this.arrListDown.userList = arr
      }
    },

    handleSelectChange (model, value) {
      console.log('model: ', model)
      console.log('value: ', value)
      this.formData[model] = value
      this.userId = value ? value : JSON.parse(localStorage.getItem('clientLoginInfo')).data.userId
    }
  } // methods end
}
</script>

<style lang="scss">
// @import '@/assets/styles/dailyManage.less';
</style>
